<template>
  <div class="coupon">
    <!-- 面包屑导航 -->
    <div class="center-w">
      <div class="head">
        <div class="title">礼包管理</div>
        <div class="add">
          <el-button type="success" @click="addCoupon">添加礼包</el-button>
          <el-input
            @input="getCouponPackList"
            v-model="pageparm.name"
            placeholder="请输入"
            style="width: 250px; "
          >
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
        </div>
      </div>
      <div style="overflow-y: scroll;height: 100%;">
        <el-table size="mini" :data="tableData">
          <el-table-column type="index" align="center" label="">
          </el-table-column>
          <el-table-column
            prop="backImg"
            align="center"
            width="100"
            label="图片"
          >
            <template slot-scope="scope">
              <el-image
                style="width: 40px; height: 40px;"
                :src="scope.row.backImg"
              >
                <div slot="error" class="image-slot">
                  <el-image :src="require('../../assets/img/lolo.png')">
                  </el-image>
                </div>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column
            prop="name"
            align="center"
            width="250"
            label="礼包名"
          ></el-table-column>
          <el-table-column prop="sort" width="180" align="center" label="排序"></el-table-column>
          <el-table-column prop="salesPrice" width="180" align="center" label="售价"></el-table-column>
          <el-table-column
            prop="createTime"
            align="center"
            label="创建时间"
          ></el-table-column>
          <el-table-column prop="roleName" align="center" label="礼包开关">
            <template slot-scope="scope">
              <el-switch
                @change="updateState(scope.row)"
                v-model="scope.row.active"
              ></el-switch>
              <span style="margin-left: 10px;">
                {{ scope.row.active ? "开" : "关" }}
              </span>
            </template>
          </el-table-column>

          <el-table-column
            fixed="right"
            width="280"
            align="center"
            label="操作"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                @click="updateCurrentCoupon(scope.row.id)"
                >编辑</el-button
              >
              <el-button
                size="mini"
                type="danger"
                @click="deleteCurrentItem(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页组件 -->
      <Pagination
        v-bind:child-msg="pageparm"
        @callFather="callFather"
      ></Pagination>
    </div>

    <!-- 新增 编辑礼包 -->
    <el-dialog
      :title="currentFlag == 1 ? '新增礼包' : '编辑礼包'"
      :visible.sync="addCouponShow"
      width="700px"
      top="50px"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="150px"
        class="demo-ruleForm"
      >
        <el-form-item label="礼包名：" prop="name">
          <el-input v-model="ruleForm.name" size="small"></el-input>
        </el-form-item>
        <el-form-item label="排序：" prop="sort">
          <el-input
            v-model="ruleForm.sort"
            type="number"
            size="small"
          ></el-input>
        </el-form-item>
        <el-form-item label="礼包图片：" prop="backImg">
          <template>
            <upload-img
              :isShowTip="false"
              :limit="1"
              :value="ruleForm.backImg"
              @input="uploadImgBack($event)"
            />
            <span style="color: red;">提示：</span>
            <span style="color: #999;"
              >默认礼包封面是鹏城测试logo，如需更改，请删除后重新上传。</span
            >
          </template>
        </el-form-item>
        <el-form-item label="优惠券选择：">
          <div
            style="display: flex;align-items: center; margin-bottom: 10px;"
            v-for="(item, index) in ruleForm.items"
            :key="index"
          >
            <el-select
              v-model="item.couponId"
              placeholder="请选择"
              style="width: 228px;"
              size="small"
              @change="changeCoupon()"
            >
              <el-option
                v-for="items in couponOptions"
                :key="items.id"
                :label="items.name"
                :value="items.id"
              >
              </el-option>
            </el-select>
            <el-input
              v-model="item.count"
              type="number"
              placeholder="数量"
              style="width: 80px;margin:0 15px;"
              size="small"
            ></el-input>
            <el-button
              type="danger"
              icon="el-icon-minus"
              circle
              @click="delCouponItem()"
              size="mini"
              v-if="index == ruleForm.items.length - 1 && index != 0"
            ></el-button>
            <el-button
              type="primary"
              icon="el-icon-plus"
              circle
              @click="addCouponItem()"
              v-if="index == 0"
              size="mini"
              style="width: 30px;height: 30px;"
            ></el-button>
          </div>
        </el-form-item>
        <el-form-item label="显示原价：" prop="unitPrice">
          <el-input
            v-model="ruleForm.unitPrice"
            type="number"
            size="small"
          ></el-input>
        </el-form-item>
        <el-form-item label="售卖价格：" prop="salesPrice">
          <el-input
            v-model="ruleForm.salesPrice"
            type="number"
            size="small"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注：" prop="notes">
          <el-input v-model="ruleForm.notes" type="textarea" size="small" style="width: 400px;"></el-input>
        </el-form-item>
        <el-form-item label="购买限制：" prop="isLimit">
          <el-radio-group @change="checkBuy" v-model="ruleForm.isLimit">
            <div style="display: flex;align-items: center;">
              <el-radio :label="false" style="margin-right: 10px;">
                <span>无限制购买</span>
              </el-radio>
              <div style="margin-bottom: 15px;"></div>
              <el-radio
                :label="true"
                style="margin-right: 10px;"
                :disabled="checkedGroup.length > 1"
              >
                <span>
                  用户仅可购买
                  <el-input-number
                    v-model="ruleForm.limit"
                    :min="1"
                    :disabled="!ruleForm.isLimit"
                    size="small"
                    style="width: 120px;"
                  ></el-input-number>
                  张</span
                >
              </el-radio>
            </div>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCouponShow = false">取 消</el-button>
        <el-button @click="submitAuthority('ruleForm')" type="primary">{{
          currentFlag == 0 ? "编辑" : "新增"
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "../../components/Pagination";
import uploadImg from "../../components/uploadImg";

import { getCouponList } from "../../api/coupon";
import {
  createCouponPack,
  getCouponPackList,
  getCouponpackById,
  updateCouponpack,
  delectCouponpack,
  setCouponpackState
} from "../../api/couponPack";

export default {
  data() {
    return {
      addCouponShow: false,
      currentFlag: 0,
      ruleForm: {
        id: null,
        name: "", //名称
        sort: "",
        backImg: [
          { url: "http://applet.atptest.com/RtTk5Oca1682497720771.png" }
        ],
        unitPrice: "",
        salesPrice: "",
        notes: "",
        isLimit: null,
        limit: "",
        items: [
          {
            couponId: null,
            count: ""
          }
        ]
      },
      checkedGroup: [],
      couponList: [],
      list: [],
      userList: [],
      couponOptions: [],
      rules: {
        name: [
          { required: true, message: "请输入礼包名称", trigger: "blur" },
        ],
        sort: [{ required: true, message: "请输入排序值", trigger: "blur" }],
        unitPrice: [{ required: true, message: "请输入原价", trigger: "blur" }],
        salesPrice: [
          { required: true, message: "请输入售价", trigger: "blur" }
        ],
        notes: [{ required: true, message: "请输入备注", trigger: "blur" }],
        isLimit: [
          { required: true, message: "请选择购买限制", trigger: "change" }
        ]
      },
      pageparm: {
        pageIndex: 1,
        pageSize: 10,
        name: "",
        total:0
      },
      //优惠券请求搜索条件
      pageparmCoupon: {
        pageIndex: 1,
        pageSize: 999,
        searchKey: ""
      },
      tableData: []
    };
  },
  name: "coupon",
  components: {
    Pagination,
    uploadImg //上传图片
  },

  created() {
    this.getCouponPackList();
    this.getCouponList();
  },

  methods: {
    //获取优惠券列表
    async getCouponList() {
      const res = await getCouponList(this.pageparmCoupon);
      if (res.code == 200) {
        this.couponOptions = res.data.items;
      } else {
        this.couponOptions = [];
      }
    },

    //获取礼包列表
    async getCouponPackList() {
      const res = await getCouponPackList(this.pageparm);
      if (res.code == 200) {
        let { items, totalCount } = res.data;
        this.tableData = items;
        this.pageparm.total = totalCount;
      } else {
        this.$message.error(res.message);
      }
    },

    // 查询礼包名字
    inputSearch(val) {
      this.pageparm.searchKey = val;
      this.pageparm.pageIndex = 1;
      this.getCouponPackList();
    },

    //增加优惠券选择
    addCouponItem() {
      this.ruleForm.items.push({
        couponId: null,
        count: ""
      });
    },

    //减少优惠券
    delCouponItem() {
      this.ruleForm.items.pop();
    },

    //购买限制
    checkBuy(val) {
      if (!val) {
        this.ruleForm.limit = 0;
      }
    },

    //开关控制
    updateState(r) {
      this.$confirm(`确认${r.active ? "打开" : "关闭"}吗? `, "确认信息", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(() => {
          setCouponpackState({
            isActive: r.active,
            id: r.id,
            updateBy: JSON.parse(localStorage.getItem("info")).id
          }).then(res => {
            if (res.code == 200) {
              this.$message.success(`已${r.active ? "打开" : "关闭"}`);
              this.getCouponPackList();
            }
          });
        })
        .catch(action => {
          this.$message.info("取消操作");
          this.getCouponPackList();
        });
    },

    // 新增礼包
    addCoupon() {
      this.addCouponShow = true;
      this.currentFlag = 1;
      this.ruleForm = {
        name: "", //名称
        sort: "",
        backImg: [
          { url: "http://applet.atptest.com/RtTk5Oca1682497720771.png" }
        ],
        unitPrice: "",
        salesPrice: "",
        notes: "",
        isLimit: "",
        limit: "",
        items: [
          {
            couponId: null,
            count: ""
          }
        ]
      };
      this.$refs["ruleForm"].resetFields();
    },

    //确认提交
    submitAuthority(ruleForm) {
      this.$refs[ruleForm].validate(valid => {
        if (valid) {
          for (let i = 0; i < this.ruleForm.items.length; i++) {
            if (
              this.ruleForm.items[i].couponId == null ||
              !this.ruleForm.items[i].count || Number(this.ruleForm.items[i].count) <= 0
            ) {
              this.$message.error("优惠券信息未填写完整或数量填写有误");
              return;
            }
          }
          if (this.ruleForm.backImg instanceof Array) {
            this.ruleForm.backImg = this.ruleForm.backImg[0].url;
          }
          // 新增
          if (this.currentFlag == 1) {
            createCouponPack(this.ruleForm).then(res => {
              if (res.code == 200) {
                this.$message.success("新增成功");
                this.addCouponShow = false;
                this.getCouponPackList();
              } else {
                this.$message.error(res.message);
              }
            });
          } else {
            //编辑
            updateCouponpack(this.ruleForm).then(res => {
              if (res.code == 200) {
                this.$message.success("编辑成功");
                this.addCouponShow = false;
                this.getCouponPackList();
              } else {
                this.$message.error(res.message);
              }
            });
          }
        } else {
          // alert("error submit!!");
          return false;
        }
      });
    },

    //获取详情
    async updateCurrentCoupon(id) {
      this.ruleForm.id = id;
      let res = await getCouponpackById({ id });
      if (res.code == 200 && res.data) {
        this.currentFlag = 0;
        this.addCouponShow = true;
        let obj = res.data;
        for (const key in obj) {
          for (const car in this.ruleForm) {
            if (key == car) {
              this.ruleForm[car] = obj[key];
            }
          }
        }
        this.ruleForm.items = obj.items.map(item => {
          return {
            couponId:item.couponId,
            count:item.count
          }
        })
      } else {
        this.$message.error(res.message);
      }
    },

    // 删除某个礼包
    deleteCurrentItem(e) {
      this.$confirm("您确定要删除吗？", "删除确认", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定删除",
        cancelButtonText: "取消"
      })
        .then(() => {
          if (e.id) {
            delectCouponpack({ ids: [e.id] }).then(res => {
              if (res.code == 200) {
                this.$message.success("删除成功");
                this.getCouponPackList();
              } else {
                this.$message.error(res.message);
                this.getCouponPackList();
              }
            });
          }
        })
        .catch(action => {
          this.$message.info("取消删除");
        });
    },

    // 上传图片的回调
    uploadImgBack(x) {
      if (x && x.length > 0) this.ruleForm.backImg = x[0].url;
    },

    // 分页插件事件
    callFather(parm) {
      this.pageparm.pageIndex = parm.pageIndex;
      this.pageparm.pageSize = parm.size;
      this.getCouponPackList();
    }
  }
};
</script>

<style lang="less" scoped>
.center-w {
  display: flex;
  /* align-items: center; */
  flex-direction: column;
  background-color: #fff;
  height: 80vh;
  padding: 20px;
  border: 1px solid #ccc;
  margin: 20px;
  .title {
    color: rgba(16, 16, 16, 1);
    font-size: 20px;
    margin-bottom: 10px;
  }
  .add {
    .el-input {
      margin-left: 20px;
    }
  }
  .head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;
  }

  .active {
    color: green !important;
  }
}
.el-input {
  max-width: 300px !important;
}
input {
  text-align: center;
  border-radius: 5px;
  width: 40px;
  height: 25px;
  outline: none;
  margin: 0 10px;
  border: 1px solid #ccc;
}
</style>
